"""
Flask application configuration.
Loads configuration from environment variables using python-dotenv.
"""
import os
from datetime import timedelta
from pathlib import Path

# Load environment variables from .env file
from dotenv import load_dotenv

# Get the base directory of the application
basedir = Path(__file__).resolve().parent.parent

# Load .env file if it exists
env_path = basedir / '.env'
if env_path.exists():
    load_dotenv(env_path)


class Config:
    """Base configuration class with common settings."""

    # Flask Core Settings
    SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key-change-in-production')

    # Database Configuration
    SQLALCHEMY_DATABASE_URI = os.getenv(
        'DATABASE_URL',
        f'sqlite:///{basedir / "instance" / "ruiyun.db"}'
    )
    SQLALCHEMY_TRACK_MODIFICATIONS = False  # Disable event system for performance

    # SQLite-specific engine options
    SQLALCHEMY_ENGINE_OPTIONS = {
        'connect_args': {
            'check_same_thread': False,  # Allow multi-threaded access
        },
        'pool_pre_ping': True,  # Verify connections before use
    }

    # File Upload Configuration
    MAX_CONTENT_LENGTH = 10 * 1024 * 1024  # 10MB maximum file size

    # Session Configuration
    SESSION_COOKIE_HTTPONLY = True  # Prevent JavaScript access to session cookie
    SESSION_COOKIE_SAMESITE = 'Lax'  # CSRF protection
    SESSION_COOKIE_SECURE = os.getenv('SESSION_COOKIE_SECURE', 'False').lower() == 'true'  # HTTPS only in production
    PERMANENT_SESSION_LIFETIME = timedelta(
        seconds=int(os.getenv('PERMANENT_SESSION_LIFETIME', 1800))  # Default: 30 minutes
    )

    # URL scheme configuration for reverse proxy
    PREFERRED_URL_SCHEME = os.getenv('PREFERRED_URL_SCHEME', 'http')  # Use 'https' in production

    # Flask Environment
    FLASK_ENV = os.getenv('FLASK_ENV', 'development')
    DEBUG = FLASK_ENV == 'development'


class DevelopmentConfig(Config):
    """Development environment configuration."""
    DEBUG = True
    TESTING = False


class ProductionConfig(Config):
    """Production environment configuration."""
    DEBUG = False
    TESTING = False
    # Don't force HTTPS - let environment variable control this
    # SESSION_COOKIE_SECURE can be set via environment variable


class TestingConfig(Config):
    """Testing environment configuration."""
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'  # In-memory database for tests
    WTF_CSRF_ENABLED = False  # Disable CSRF for easier testing


# Configuration dictionary
config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}
